# -*- coding:Utf-8 -*-
'''
Created on 25 nov. 2012

@author: fefoley
'''

import calendar, datetime

from workday import WorkDay
import myio, myalgo, divers


"""tmp comment"""




#########################################################

if __name__ == "__main__":
 
    # file constantes - could be automated using an explorer to choose file
    input_root_path = "/home/test-dev/reverse_hours.io/"
    path_to_configfile = input_root_path + "reverse_hours.config.txt"
        
    "importation des paramètres de config"
    config = myio.import_config(path_to_configfile)
    
    "importation des données dans des listes"
    lstmails = myio.import_mails(config) # importer la liste des mails et retourne une liste d'objet Mail
    lstmeetings = myio.import_meetings(config) # importer la liste des réunions et retourne une liste d'objet Meeting
    lstsentmeetings = myio.import_sentmeetings(config) # importer la liste des réunions et retourne une liste d'objet Meeting
    lstholidays = myio.import_holidays(config) # importer la liste des jours fériés et retourne une liste d'objet datetime.date
    lstdaysoff = myio.import_daysoff(config) # importer la liste des congés et retourne une liste d'objet datetime.date
    
    'create the dictionary entry of the workdays and of the weeks'
    str_start = config.get('workday','startday')
    str_end = config.get('workday','endday')
    wdstart = datetime.datetime.strptime(str_start, "%d/%m/%Y")
    wdend = datetime.datetime.strptime(str_end, "%d/%m/%Y")
    wddico = divers.wddico_init(wdstart, wdend)
    weekdico = divers.weekdico_init(wdstart, wdend, wddico)
    
    'add holidays'
    for (holiday_date, holiday_name) in lstholidays:    #holiday = (date, name)
        wd = divers.wddico_getday(wddico, holiday_date)
        if wd: wd.setholiday(holiday_name)
    
    'add dayoffs'
    for (start, end, strtype, nbday) in lstdaysoff:     #dayoff = (startdate, enddate, typedayoff, length)
        "loop from start to end with +1day"
        if start > end:  # check start > end, otherwise could have endless loop
            raise Exception("FromDate > ToDate in dayoffs data!")
        while start <= end:
            "find the WorkDay set the dayoff to it"
            wd = divers.wddico_getday(wddico, start)
            if wd: wd.setdayoff(strtype)
            start += datetime.timedelta(days=1)
                
    'add mails'
    for mail in lstmails:
        wd = divers.wddico_getday(wddico, mail.getsentdatetime())
        if wd: wd.addmail(mail)
    
    'add meetings' 
    # Commencer avec pre-processing des meetings --> avoir des meetings uniquement à l'intérieur d'une journée  ??
    lstmeetings = myalgo.preprocess_meeting(lstmeetings)
    for meeting in lstmeetings: 
        'add the meeting to the day it is happening'
        wd = divers.wddico_getday(wddico, meeting.getdatetime())         
        if wd: wd.addmeeting(meeting)   

    'add sentmeetings' 
    for sentmeeting in lstsentmeetings: 
        'add the sent meeting to the day it was sent if I sent it'
        wd = divers.wddico_getday(wddico, sentmeeting.getsentdatetime())         
        if wd: wd.addsentmeeting(sentmeeting)   

    
    
    'creation of the timestrip'
    for _, year in wddico.items():
        for month in year:
            for wday in month:
                if wday:
                    wday.create_timestrips()    
    
#    'heures non ouvrées'
#    HOstart = datetime.time(6, 0, 0)
#    HOend = datetime.time(22, 0, 0)
    
    
    'aggregatetion of the timestrips'
    
    for _, year in wddico.items():
        for month in year:
            for wday in month:
                if wday:
                    wday.aggregate_timestrips()       
    
#    for _, year in weekdico.items():
#        for week in year:
#            for i in range(0, 7):
#                if week[i]:
#                    week[i].aggregate_timestrips()
#                    print("{0}\tHO: {1}\tHNO: {2}".format(week[i], 
#                                                          week[i].worktimescope(HOstart, HOend),
#                                                          week[i].worktimescope(HOend, HOstart)))
            
    
        
    #Optimisation des TimesStrip
    

    """
    impression des TimeStrip  pour import dans Excel
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label
    """
    lst_timestrips =[]
    for key, year in wddico.items():
        for month in year:
            for wday in month:
                if wday: lst_timestrips.append(wday.timestrips)
        
    
    lst_timestrips = [sorted(s) for s in lst_timestrips]
 
    
    myio.output_timestrip(lst_timestrips, config)


    """
    output all off days (holidays, dayoffs, WE)
    YYYY/MM/DD    WE/Holyday/Dayoff    ALL/AM/PM    Name
    """

    myio.output_alldayoffs(wddico, config)



    """
    Debug timestrip OFF
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label
    """
#    lst_timestrips =[]
#    for key, year in wddico.items():
#        for month in year:
#            for wday in month:
#                if wday: lst_timestrips.append(wday.timestrips_off)
#    str_debug = ""
#    for timestrips in lst_timestrips:
#        for ts in timestrips:
#            line = ts.dtstart.strftime("%Y/%m/%d") + '\t' + ts.dtstart.strftime("%H:%M") \
#                                                 + '\t' + ts.dtend.strftime("%H:%M") \
#                                                 + '\t' + ts.content.getlabel().replace('\t','\\utab').replace('\n','\\ueol') \
#                                                 + '\n'
#            str_debug  = str_debug + line
#                               
#    myio.debug_output(str_debug, config)

    